package neu.tour.activity;

import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.hardware.Camera;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.SurfaceView;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.SeekBar;

import org.opencv.android.BaseLoaderCallback;
import org.opencv.android.LoaderCallbackInterface;
import org.opencv.android.OpenCVLoader;

import java.io.IOException;

import neu.tour.R;
import neu.tour.support.CameraPreview;
import neu.tour.support.InitSystemBar;
import neu.tour.support.SaveDataToFile;


@SuppressWarnings("deprecation")
public class CameraActivity extends Activity{

    private ImageView takeView; //拍照按钮
    private Button editButton;  //确认按钮
    private Button cancelButton;  //取消按钮
    private CameraPreview cameraPreview;//预览
    private SurfaceView surfaceView;//预览的View
    private Bundle bundle = null;  // 声明一个Bundle对象，用来存储数据
    private String savePath = "/AATour/camera"; //存储拍摄照片的路径
    private SeekBar seekbar;
    private WindowManager.LayoutParams lp;
    private int selectedImgId;
    private SaveDataToFile s;

    private BaseLoaderCallback mLoaderCallback = new BaseLoaderCallback(this) {
        @Override
        public void onManagerConnected(int status) {
            switch (status) {
                case LoaderCallbackInterface.SUCCESS:{
                    Log.i("CameraActivity", "Load success");
                } break;
                default:{
                    super.onManagerConnected(status);
                } break;
            }
        }
    };


    @TargetApi(Build.VERSION_CODES.HONEYCOMB)
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        InitSystemBar.initSystemBar(this);
        setContentView(R.layout.activity_camera);

        if (!OpenCVLoader.initDebug()) {
            OpenCVLoader.initAsync(
                    OpenCVLoader.OPENCV_VERSION_3_1_0,
                    this, mLoaderCallback);
        } else {
            mLoaderCallback.onManagerConnected(
                    LoaderCallbackInterface.SUCCESS);
        }


        Intent intent = getIntent();
        Bundle bundle = intent.getExtras();//从上一个Activity获取参数图片
        selectedImgId = bundle.getInt("selectedImgId");
        // new 一个CameraPreiew
        surfaceView = (SurfaceView)findViewById(R.id.surfaceView);
        cameraPreview = new CameraPreview(
                this, this, surfaceView, selectedImgId);
        cameraPreview.setFocusable(true);
        s = new SaveDataToFile(savePath, 0);

        initSeekBar();
        initTakeView();
        initEditButton();
        initCancelButton();
        setVisibile(true);
    }


    /**
     * 初始化滑块儿
     */
    private void initSeekBar() {
        lp = getWindow().getAttributes();
        seekbar = (SeekBar) findViewById(R.id.seekBar);
        seekbar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener(){
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress,
                                          boolean fromUser) {
                lp.screenBrightness = (float)progress/100;
                getWindow().setAttributes(lp);
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
                // TODO Auto-generated method stub
            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                // TODO Auto-generated method stub
            }
        });
    }


    /**
     * 初始化拍照按钮
     */
    private void initTakeView() {
        takeView = (ImageView) findViewById(R.id.btn_takepicture);
        takeView.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View view) {
                Camera camera = cameraPreview.camera;
                if (camera != null) {
                    camera.takePicture(null, null, new MyPictureCallback());
                }
                setVisibile(false);
            }
        });
    }


    /**
     * 初始化取消按钮
     */
    private void initCancelButton() {
        cancelButton = (Button) findViewById(R.id.bnt_cancel);
        cancelButton.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View view) {
                Camera camera = cameraPreview.camera;
                setVisibile(true);
                if (camera != null) {
                    try {
                        camera.startPreview(); // 开始预览
                    }catch (RuntimeException e){
                        camera.release();
                    }
                }
            }
        });
    }


    /**
     * 初始化编辑按钮
     */
    private void initEditButton() {
        editButton = (Button) findViewById(R.id.bnt_enter);
        editButton.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View view) {
                byte[] data = bundle.getByteArray("bytes");
                BitmapFactory.Options options = new BitmapFactory.Options();
                options.inTempStorage = new byte[1024 * 1024 * 1];//压缩到1MB
                options.inSampleSize = 2;
                Bitmap picbitmap = BitmapFactory.decodeByteArray(
                        data, 0, data.length, options);
                Matrix m = new Matrix();
                m.setRotate(90);
                Bitmap savebitmap = Bitmap.createBitmap(picbitmap, 0, 0,
                        picbitmap.getWidth(), picbitmap.getHeight(), m,true);
                try {
                    s.saveToSDCard(savebitmap);
                }catch (IOException e) {
                    e.printStackTrace();
                }
                Intent intent = new Intent();
                intent.setClass(CameraActivity.this, EditActivity.class);
                intent.putExtra("filename", s.getFilename()); //传参数
                intent.putExtra("selectedImgId", selectedImgId);
                CameraActivity.this.startActivity(intent);
                finish();
            }
        });
    }

    /**
     * 设置可见 or 不可见
     */
    private void setVisibile(boolean isVisible) {
        if (isVisible){
            seekbar.setVisibility(View.VISIBLE);
            takeView.setVisibility(View.VISIBLE);
            cancelButton.setVisibility(View.INVISIBLE);
            editButton.setVisibility(View.INVISIBLE);
        } else {
            seekbar.setVisibility(View.INVISIBLE);
            takeView.setVisibility(View.INVISIBLE);
            cancelButton.setVisibility(View.VISIBLE);
            editButton.setVisibility(View.VISIBLE);
        }
    }


    /**
     * 重构照相类
     */
    private final class MyPictureCallback implements Camera.PictureCallback {

        @Override
        public void onPictureTaken(byte[] data, Camera camera) {
            try {
                bundle = new Bundle();
                //将图片字节数据保存在bundle当中，实现数据交换
                bundle.putByteArray("bytes", data);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }


    @Override
    protected void onStop(){
        super.onStop();
    }


    @Override
    protected void onDestroy(){
        super.onDestroy();
    }


    @Override
    protected void onResume(){
        super.onResume();
    }


    @Override
    protected void onPause(){
        super.onPause();
    }
}